import BMapApp from './BMapApp';
import VGE from '../../VGE';

export class Camera {
	constructor(viewer) {
		this.viewer = viewer;
	}

	/**
	 * 查询视角参数
	 * @returns {Promise<{heading: *|{getFreeCameraOptions}, lon: *, pitch: *, lat: *, height: *}>}
	 */
	async getCameraParams(original = true) {
		try {
			const map = this.viewer;
			const pitch = map.getTilt();
			const heading = +map.getHeading();
			const center = map.getCenter();
			const zoom = map.getZoom();
			const result = {
				lon: center.lng,
				lat: center.lat,
				height: 0,
				heading,
				pitch,
				zoom
			};

			if (!original) {
				result.height = Math.exp((28.806 - zoom) / 1.471);
				result.heading = result.heading < 0 ? 360 + (result.heading % 360) : result.heading % 360;
				result.original = 'VGE-CAMERA';
			}

			return result;
		} catch (e) {
			console.error(e.message);
		}
	}

	/**
	 * 飞到给定视角
	 * @param cameraParams
	 * @param duration
	 * @returns {Promise<void>}
	 */
	async flyTo(cameraParams, duration = 1) {
		if (!VGE.util.validateCameraParams(cameraParams)) return;
		try {
			let { lon, lat, height, heading, pitch, zoom } = cameraParams;

			if (cameraParams.original === 'VGE-CAMERA') {
				// 高德地图为火星坐标系需要转换
				heading = heading % 360;
				heading = heading > 180 ? heading - 360 : heading;
				heading = heading < -180 ? heading + 360 : heading;
				zoom = zoom || 28.806 - Math.log(height) * 1.471;
			}

			const BMap = this.viewer;
			BMap.addEventListener('load', () => {
				BMap.removeEventListener('load');
				BMap.setZoom(zoom);
			});
			BMap.centerAndZoom(new window.BMapGL.Point(lon, lat), zoom);
			BMap.setHeading(heading);
			BMap.setTilt(pitch);
		} catch (e) {
			console.error(e.message);
		}
	}

	/**
	 * 主视角
	 * @returns {Promise<void>}
	 */
	async homeView() {
		this.flyTo(BMapApp.homeViewParams);
	}
}
